package com.ty.skysystem.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.skysystem.dao.CarriersDao;
import com.ty.skysystem.entity.CarriersEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.common.utils.PageUtils;
import com.ty.common.utils.Query;

import com.ty.skysystem.dao.SchedulingDao;
import com.ty.skysystem.entity.SchedulingEntity;
import com.ty.skysystem.service.SchedulingService;
import org.springframework.transaction.annotation.Transactional;

@Service("schedulingService")
public class SchedulingServiceImpl extends ServiceImpl<SchedulingDao, SchedulingEntity>
    implements SchedulingService {

  @Autowired private CarriersDao carriersDao;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<SchedulingEntity> page =
        this.page(
            new Query<SchedulingEntity>().getPage(params),
            new QueryWrapper<SchedulingEntity>()
                .select(SchedulingEntity.class, e -> !"is_deleted".equals(e.getColumn())));

    return new PageUtils(page);
  }

  /**
   * 将现有未调度承运单任务分配给现有未参与调度的已绑定驾驶员的车辆
   *
   * @param schedulingEntity 调度任务信息实体类
   * @return
   */
  @Transactional(rollbackFor = {RuntimeException.class})
  @Override
  public boolean saveScheduling(SchedulingEntity schedulingEntity) {
    // 添加新的调度任务
    int i = this.baseMapper.insert(schedulingEntity);
    // 修改承运单
    CarriersEntity carriersEntity = new CarriersEntity();
    carriersEntity.setCarriersId(schedulingEntity.getCarriersId());
    carriersEntity.setFinishedState(1);
    carriersEntity.setUserId(schedulingEntity.getUserId());
    int j = carriersDao.updateById(carriersEntity);
    if (i <= 0 || j <= 0) {
      throw new RuntimeException("网络异常,请重试");
    }
    return true;
  }

  @Override
  public PageUtils queryPageScheduling(
      Integer page, Integer limit, SchedulingEntity schedulingEntity) {

    IPage<SchedulingEntity> schedulingEntityIPage =
        baseMapper.queryPageScheduling(new Page<SchedulingEntity>(page, limit), schedulingEntity);

    return new PageUtils(schedulingEntityIPage);
  }
}
